<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Session;
use think\Request;

class Role extends Admincoetroller
{   

    //显示角色页面
   public function role()
    {
        $list=Db::name('user')->field('name')->where('username="'.Session::get('name').'"')->find();
        $sql=db('role')->select();
        // var_dump($sql);
        // die;
        return $this->fetch('user/role',['name'=>$list['name'],'userlist'=>$sql]);
    }


    //加载添加角色页面
    public function addrole()
    {   

        $list=Db::name('user')->field('name')->where('username="'.Session::get('name').'"')->find();
        return $this->fetch('user/addrole',['name'=>$list['name']]);
    }


    // 添加角色
    public function dorole(Request $request)
    {
        $sql = $request->post();
        $sql['status']='1';
        $sql=Db::name('role')->insert($sql);
        return $this->success('成功',url('role/role'));
    }


    //删除角色
    public function beleterole($id)
    {
        // var_dump($id);

        $sql=Db::name('role')->delete(['id'=>$id]);
        return $this->success('删除成功',url('role/role'));

    }

    // 分配权限
    public function getqx($id)
    {
        $list=Db::name('user')->field('name')->where('username="'.Session::get('name').'"')->find();

        $role = Db::name('role')->where('id',$id)->find();
        $nodes = Db::name('node')->where('status', 1)->select();
        $nodelist = Db::name('role_node')->where('rid',$id)->select();

        $nodelists = array();
        foreach ($nodelist as $v){
            $nodelists[] = $v['nid'];
        }
        $id=$role['id'];
        // var_dump($id);
        // die;
        return view('user/gg',[
            'name'=>$list['name'],
            "nodes" => $nodes,
            "id" => $id,
            'nodelist' => $nodelists
        ]);

        
    }

    public function Submit(Request $request )
    {   
        $sql = $request->post();
        // var_dump($sql['rid']);
        // $sql['nid']['0']=null;
        if(empty($sql['nid'])){
            return $this->error('必须选择至少一个节点');
        }
        var_dump($sql['nid']['0']);die;
        
        $nids = array();
        foreach ($sql['nid'] as $k => $v) {
            $nids[] = $v;
        }

        $rids = $sql['rid'][0];
        // var_dump($nids);die;
        // $nid = $sql['role'];
        // $nids = $nid['nid'];
        // var_dump($nids);
        Db::name('role_node')->where('rid = '.$rids)->delete();


        foreach ($nids as $k => $v) {

                $role_node['rid'] = $rids;
                $role_node['nid'] = $v;
                $data = Db::name('role_node')->data($role_node)->insert();
        }
        return $this->success('更改成功',url('role/role'));
        var_dump($role_node);
        var_dump($role_node['nid']);

        // var_dump($sqls);
        // die;
    }

}



